#include <iostream>
#include <string>
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <unordered_map>
class DictServe
{
public:
    DictServe(int port)
        : _server(&_eloop, muduo::net::InetAddress("0.0.0.0", port), "DictServe", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServe::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServe::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void Start()
    {
        _server.start();
        _eloop.loop();
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            std::cout << "链接成功" << std::endl;
        }
        else
        {
            std::cout << "conn fail" << std::endl;
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::unordered_map<std::string, std::string> dict_map = {{"hello", "你好"}, {"apple", "苹果"}, {"banana", "香蕉"}, {"pear", "梨子"}};
        std::string msg = buf->retrieveAllAsString();
        std::string res;
        auto it = dict_map.find(msg);
        if (it == dict_map.end())
        {
            res = "未知单词";
        }
        else
        {
            res = it->second;
        }
        conn->send(res);
    }

private:
    muduo::net::EventLoop _eloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServe serve(8080);
    serve.Start();
    return 0;
}